<!-- create job group -->
<template>
    <el-card>
        <Table :data="tableData" :column="tableTitle" :operation="true" :page="page" :loading="loading"
            @onSizeChange="onSizeChange" @onCurrentChange="onCurrentChange" @setCellColor="setCellColor">
            <template #search>
                <div><el-button type="primary" @click="onAddJobGroup">添加工作组</el-button></div>
                <div><el-input v-model="searchForm.jobGroupName" placeholder="请输入工作组名称"></el-input></div>
                <div><el-button @click="onRefresh" icon="RefreshRight" circle></el-button></div>
                <div><el-button @click="onSearch" type="primary" icon="Search">查询</el-button></div>
            </template>
            <template #column="scope">
                <el-button @click="onEdit(scope)" type="text" style="color:var(--edit)">编辑</el-button>
                <el-button @click="onDelete(scope)" type="text" style="color:var(--delete)">删除</el-button>
                <el-button @click="onStore(scope)" type="text" style="color:var(--store)">下载</el-button>
            </template>
        </Table>

        <el-dialog :title="jobGroupTitle" v-model="jobGroupVisible" :show-close="false">
            <el-form :model="jobGroupForm" :rules="rules" status-icon label-width="100px"
                style="padding-top: 20px; padding-bottom: 20px;">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item prop="name" label="任务组名称" :rules="[
                            { required: true, message: '请输入任务组名称', trigger: 'blur' },]">
                            <el-input v-if="operate == 0" v-model="jobGroupForm.name" placeholder="请输入任务组名称"></el-input>
                            <el-input v-if="operate == 1" v-model="jobGroupForm.name" placeholder="请输入任务组名称"></el-input>
                            <el-input v-if="operate == 2" disabled v-model="jobGroupForm.name"
                                placeholder="请输入任务组名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="jobGroupVisible = false">取消</el-button>
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                </span>
            </template>
        </el-dialog>
        <el-progress :percentage="downloadProgress" v-show="showProgress"></el-progress>
    </el-card>
</template>

<script setup>
import { reactive, toRefs, onMounted } from 'vue';
import { saveFaceJobGroup, updateFaceJobGroup, FaceJobGroupPage, FaceJobGroupPagePlus, delFaceJobGroup, apiDownloadFile } from '../../api/systemApi.js'
import Table from '../../components/Table.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useJobGroupStore } from '../../store/settings';

const jobGroupStore = useJobGroupStore();

const state = reactive({
    searchForm: {
        jobGroupName: null,
    },
    loading: false,
    page: {
        pageNum: 1,
        pageSize: 10,
        total: 1,
    },
    tableTitle: [
        { prop: '', label: '', fixed: 'left' },
        { prop: 'jobGroupId', label: 'id' },
        { prop: 'jobGroupName', label: '名称' },
        { prop: 'createBy', label: '创建人' },
        { prop: 'createTime', label: '创建时间' },
        { prop: 'updateBy', label: '修改人' },
        { prop: 'updateTime', label: '修改时间' },
    ],
    tableData: [],
    jobGroupId: null,
    jobGroupVisible: false,
    jobGroupTitle: "添加工作组",
    operate: 0,
    jobGroupForm: {
        id: '',
        name: '',
    },
    jobSort: 1, // 固定值
    command: 'step1_extract_images_from_video_data_src.bat'
});

// 从响应式状态中提取引用以在模板中使用
const { searchForm, loading, page, tableTitle, tableData, jobGroupId, jobGroupVisible, jobGroupTitle,
    operate, jobGroupForm, jobSort, command } = toRefs(state);


onMounted(() => {
    onJobGroupPage();
})

// 初始化数据
const onJobGroupPage = () => {
    state.loading = true;
    FaceJobGroupPagePlus(Object.assign(state.searchForm, state.page)).then(res => {
        state.loading = false;
        state.tableData = res.rows;
        state.page.total = res.total;
    })
}

const onSizeChange = (e) => {
    state.page.pageSize = e;
    onJobGroupPage();
}
const onCurrentChange = (e) => {
    state.page.pageNum = e;
    onJobGroupPage();
}
const onRefresh = () => {
    state.searchForm = {
        jobGroupName: null,
    }
    onJobGroupPage()
    jobGroupStore.delJobGroupId;
}

const onSearch = () => {
    onJobGroupPage()
}


// 添加作业组
const onAddJobGroup = () => {
    state.jobGroupTitle = "添加作业组";
    state.operate = 0;
    state.jobGroupForm = {
        id: '',
        name: ''
    }
    state.jobGroupVisible = true;
}

// 编辑
const onEdit = (val) => {
    state.jobGroupTitle = "修改作业组";
    state.operate = 1;
    state.jobGroupForm = {
        id: val.column.row.jobGroupId,
        name: val.column.row.jobGroupName
    }
    state.jobGroupVisible = true;
}

const onStore = (val) => {
    state.jobGroupTitle = "下载视频";
    state.operate = 2;

    state.jobGroupForm = {
        id: val.column.row.jobGroupId,
        name: val.column.row.jobGroupName
    }
    console.log("-----", state.jobGroupForm.id)
    state.jobGroupVisible = true;
}



// 删除
const onDelete = (val) => {
    ElMessageBox.confirm('此操作将删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let param = val.column.row.jobGroupId
        console.log("param", val.column.row.jobGroupId)
        delFaceJobGroup(param).then(res => {
            if (res) {
                ElMessage.success('删除成功!');
            }
        })
    }).catch(e => {
        console.log(e)
    })
}

// 提交任务的方法
// const onSubmit = async () => {
//     const jobData = {
//         ...jobGroupForm.value, // 展开jobForm对象里的所有属性
//     };

//     // 创建URLSearchParams对象
//     const params = new URLSearchParams();
//     Object.keys(jobData).forEach(key => {
//         if (jobData[key] !== null && jobData[key] !== undefined) {
//             params.append(key, jobData[key]);
//         }
//     });

//     saveFaceJobGroup(params).then(res => {
//         console.log("任务组提交成功", res);
//         if (res.data && res.code === 200 && res.data.faceJobGroupId) {
//             const jobStore = useJobStore();
//             jobStore.setJobGroupId(res.data.faceJobGroupId);
//             console.log("id", jobStore.getJobGroupId)
//         }
//     }).catch(err => {
//         console.error("任务组提交失败", err);
//     });
// };

const onSubmit = async () => {
    if (state.operate == 0) {
        const params = new URLSearchParams();
        params.append('name', state.jobGroupForm.name);
        saveFaceJobGroup(
            params
        ).then(res => {
            if (res) {
                ElMessage.success({
                    message: '添加成功！',
                    type: 'success'
                });
                state.jobGroupVisible = false;
            }
        });
    } else if (state.operate == 1) {
        //state.jobGroupForm.name = null;
        const params = new URLSearchParams();
        params.append('id', state.jobGroupForm.id);
        params.append('name', state.jobGroupForm.name);
        updateFaceJobGroup(params).then(res => {
            if (res) {
                ElMessage.success({
                    message: '修改成功！',
                    type: 'success'
                });
                state.jobGroupVisible = false;
            }
        });
    } else {
        const params = new URLSearchParams();
        params.append('id', state.jobGroupForm.id);
        apiDownloadFile(params).then(res => {
            if (res) {
                // 创建一个 blob 对象
                const blob = new Blob([res.data], { type: 'application/octet-stream' });
                // 创建一个临时 URL
                const url = URL.createObjectURL(blob);

                // 创建一个链接并触发下载
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'result.mp4');
                document.body.appendChild(link);
                link.click();

                // 释放 URL 对象
                URL.revokeObjectURL(url);

                ElMessage.success({
                    message: '下载成功',
                    type: 'success'
                });
                state.jobGroupVisible = false;
            }
        }).catch(error => {
            // 显示错误消息
            ElMessage.error({
                message: '下载失败,文件尚未生成',
                type: 'error'
            });
            console.error('下载失败：', error);
        });;
    }
};

const setCellColor = (e, callback) => {
    /**
     * e.row：表格那一行的数据
     * e.column：表格单元格那一列的信息
     */
    if (e.row.delFlag === 0 && e.column.property === 'delFlagName') {
        callback({ color: '#67C23A', fontWeight: '700' });
    } else if (e.row.delFlag === 1 && e.column.property === 'delFlagName') {
        callback({ color: '#f00', fontWeight: '700' });
    } else {
        callback({});
    }
}



</script>

<style lang="scss" scoped>
.job-group-form {
    max-width: 400px;
    /* 设置表单的最大宽度 */
    margin: 0 auto;
    /* 水平居中 */
}

// .my-card {
//     padding: 20px;
//     /* 增加卡片的内边距 */
// }
</style>
